<template>
    <div class="common userSchool">
        <innerCommon 
            :location="location"
        >
            <template slot="left">
                <span>用户列表</span>
                <a-input-search class="inputStyle" placeholder="搜索" enter-button @search="onSearch" v-model="searchValue" style="margin-left:10px" />
            </template>
            <div slot="right">
                <download 
                    :data="{'type':type}"
                    :name="'导出'"
                    :api="'manage/instituteUser/exportUser'"
                    :fileName="fileName"
                    v-if="list.length>0"
                    :formData="{type}"
                ></download>
                <a-button type="primary" style="margin-left:10px;" @click="openAddBox()">新增</a-button>
            </div>
            <div slot="table">
                <topList
                    :topList="topList"
                    :currentItem="currentItem"
                    @changeTop="changeTop"
                ></topList>
                <a-table 
                    size="middle"
                    :columns="columns" 
                    :data-source="list" 
                    :pagination="pagination"
                    :rowKey="record=>record.id"
                    @change="changePage"
                    :locale="{'emptyText': '暂无数据'}"
                    bordered>
                    <div slot="address" slot-scope="index,record">
                        {{(record.province||'')+(record.city||'')+(record.district||'')+(record.address||'')}}
                    </div>
                    <div slot="status" slot-scope="index,record">
                        <span v-if="record.status==0" style="color:green">正常</span>
                        <span v-else style="color:red">已冻结</span>
                    </div>
                    <div slot="action" slot-scope="index,record" class="tableAction">
                        <span @click="editUser(record)">修改</span>
                        <span @click="updateStatus(record)">{{record.status==1?'解冻':'冻结'}}</span>
                        <span @click="deleteUser(record)">删除</span>
                    </div>
                </a-table>
            </div>
        </innerCommon>

        <!-- 新增修改用户 -->
        <a-modal
            :title="title"
            :visible="addModel"
            @cancel="addModel=false"
            okText="确定"
            cancelText="取消"
            @ok="addUser()"
            class="addSchoolUser"
            :destroyOnClose="true"
            width="700px"
            >
            <div>
                <eform
                    v-if="fields||addOrEdit==0"
                    :formData="formData"
                    class="form"
                    ref="form"
                    :fields="fields"
                >
                    <eAddress
                        :detailAddress="true"
                        slot="address"
                        v-decorator="['addressValue',{rules: [{ required: true, message: '请选择地址' }]}]"
                        :defaultAddress='defaultAddress'
                        @changeAddress="changeAddress"
                        :isAllAddress="true"
                    ></eAddress>
                </eform>
            </div>
        </a-modal>
    </div>
</template>
<script>
const columns=[
    {
        title: '序号',
        dataIndex: 'index',
        width:70
    },{
        title: '学校名称',
        dataIndex: 'name',
    },{
        title: '账号',
        dataIndex: 'account',
    },{
        title: '联系方式',
        dataIndex: 'telephone',
    },{
        title: '联系地址',
        scopedSlots: { customRender: 'address' },
    },{
        title: '邮箱地址',
        dataIndex: 'email',
    },{
        title: '联盟单位',
        dataIndex: 'isAlliance',
    },{
        title: '试点院校',
        dataIndex: 'isTrialSite',
    },{
        title: '考核站点',
        dataIndex: 'isExamSite',
    },{
        title: '管理站点',
        dataIndex: 'isChargeSite',
    },{
        title: '创建时间',
        dataIndex: 'createTime',
    },{
        title: '状态',
        scopedSlots: { customRender: 'status' },
    },{
        title: '操作',
        scopedSlots: { customRender: 'action' },
    }
]
import {getUserSchoolListApi,updateInstituteStatusApi,addInstituteUserApi,deleteInstituteUserApi,checkPhoneApi} from "@/request/api"
import innerCommon from "@/components/common/innerCommon"
import topList from "@/components/common/topList"
import eform from "@/components/common/form"
import download from "@/components/common/download"
import eAddress from "@/components/common/eAddress"
export default {
    name:"userSchool",
    components:{innerCommon,topList,eform,download,eAddress},
    created(){
        this.type=0
        this.init()
        this.location=[{
            name:"用户管理",
            path:''
        },{
            name:"机构用户",
            path:''
        }]
    },
    watch:{
        searchValue:function(val){
            this.searchValue=val.trim()
        },
    },
    data(){
        let validatePhone=(rule,value,callback)=>{
            let reg=/^1[345789]\d{9}$/
            if(!value||reg.test(value)){
                if(!value){
                    callback(new Error(' '))
                    return
                }
                let fun=this.getToken(checkPhoneApi,{'telephone':value},res=>{
                    if(res.data.isExist){
                        callback(new Error('该号码已存在'))
                    }else{
                        callback()
                    }
                })
                if(this.addOrEdit==1){
                    if(value==this.fields.telephone){
                        callback()
                    }else{
                        fun()
                    }
                }else{
                    fun()
                }
            }else{
                callback(new Error('请输入正确格式的电话'))
            }
        }
        let validateName=(rule,value,callback)=>{
            if(value){
                if(value.trim().length === 0){
                    callback(new Error('姓名不能全是空格'))
                }else{
                    callback()
                }
            }else{
                callback()
            }
        }
        const formData=[
            {
                label:"学校名称",
                prop:"name",
                placeholder:'请输入学校名称',
                rules:[{required:true,message:'请输入学校名称'},{validator:validateName}],
            },{
                label:"手机号码",
                prop:"telephone",
                placeholder:'请输入手机号码',
                rules:[{required:true,message:'请输入手机号码'},{validator:validatePhone}],
            },{
                label:"地址",
                scopedSlots: { customRender: 'address'},
            }
        ]
        return{
            columns,
            fields:null,
            location:[],
            list:[],
            searchInfo:{
                page:1,
                pageSize:10,
                keyword:'',
                type:'0',//0学校 1企业
                status:'' //0正常 1冻结
            },
            pagination:{total:0,pageSize:10,current:1},
            searchValue:'',
            topList:[
                {
                    name:"学校用户",
                    id:0
                },{
                    name:'企业用户',
                    id:1
                }
            ],
            currentItem:'0',
            addModel:false,
            type:null,//0教师 1学生 2企业
            addOrEdit:0,//0是新增 1是修改
            formData,
            title:'',
            userId:null,
            dataList:[],
            info:{},
            fileName:'学校用户列表.xls',
            defaultAddress:[],

        }
    },
    methods:{
        init(){
            this.getToken(getUserSchoolListApi,this.searchInfo,res=>{
                this.list=res.data.rows.map((item,index)=>({
                    ...item,
                    'isAlliance':item.isAlliance?'是':'否',
                    'isChargeSite':item.isChargeSite?'是':'否',
                    'isExamSite':item.isExamSite?'是':'否',
                    'isTrialSite':item.isTrialSite?'是':'否',
                    'index':(this.searchInfo.page-1)*10+index+1,
                }))
                this.pagination.total=res.data.count
            })
        },
        updateStatus(data){
            this.$confirm({
                title: data.status==0?'冻结后，用户“'+(data.name||data.account)+'”将无法登录平台，确定冻结该账户吗？':'解冻后，用户“'+(data.name||data.account)+'”将可以登录平台，确定解冻该账户吗？',
                cancelText:"取消",
                okText:'确定',
                onOk:()=>{
                    handleOk()
                },
                onCancel() {
                },
            });
            let handleOk=()=>{
                this.getToken(updateInstituteStatusApi,{'userId':data.id,'status':data.status==0?1:0},res=>{
                    this.$message.success(res.message)
                    this.init()
                })
            }
        },
        openAddBox(){
            this.addOrEdit=0
            this.addModel=true
            this.fields=null
            if(this.type==0){
                this.title="新增学校"
            }else{
                this.title="新增企业"
            }
        },
        deleteUser(data){
            this.$confirm({
                title: "删除后，用户“"+(data.name||data.account)+"”在平台上的一切信息都不存在，确定删除该账户吗？",
                cancelText:"取消",
                okText:'确定',
                onOk:()=>{
                    handleOk()
                },
                onCancel() {
                },
            });
            let handleOk=()=>{
                this.getToken(deleteInstituteUserApi,{'userId':data.id},res=>{
                    this.$message.success(res.message)
                    this.init()
                })
            }
        },
        changePage(data){
            this.searchInfo.page=data.current
            this.pagination.current=data.current
            this.init()
        },
        onSearch(data){
            this.searchInfo.keyword=data
            this.init()
        },
        changeTop(id){
            if(id==0&&this.columns[1].title=='企业名称'){
                this.fileName='学校用户列表.xls'
                this.formData[0].label="学校名称"
                this.columns[1].title='学校名称'
                let arr=[
                    {
                        title: '试点院校',
                        dataIndex: 'isChargeSite',
                    },{
                        title: '考核站点',
                        dataIndex: 'isExamSite',
                    },{
                        title: '管理站点',
                        dataIndex: 'isTrialSite',
                    }
                ]
                this.columns.splice(7,0,...arr)
            }else if(id==1&&this.columns[1].title=='学校名称'){
                this.fileName='企业用户列表.xls'
                this.formData[0].label="企业名称"
                this.columns[1].title='企业名称'
                this.columns.splice(7,3)
            }
            this.type=id
            this.currentItem=id
            this.searchInfo.page=1
            this.searchInfo.type=id
            this.searchInfo.keyword=''
            this.pagination.current=1
            this.searchValue=''
            this.init()
        },
        changeAddress(data){
            if(data[0]&&data[3]){
                this.$refs.form.form.setFieldsValue({['addressValue']:data})
            }else{
                this.$refs.form.form.resetFields(['addressValue'])
            }
        },
        addUser(){
            this.$refs.form.form.validateFields().then(res=>{
                let api
                let formData={
                    ...res,
                    'province':res.addressValue[0],
                    'city':res.addressValue[1],
                    'district':res.addressValue[2],
                    'address':res.addressValue[3]
                }
                if(this.addOrEdit==0){
                    api=addInstituteUserApi
                }else{
                    api=updateInstituteStatusApi
                    formData={...formData,'userId':this.userId}
                }
                this.getToken(api,{...formData,'type':this.type},data=>{
                    this.$message.success(data.message)
                    this.init()
                    this.addModel=false
                })
            })
        },
        editUser(data){
            this.userId=data.id
            this.addOrEdit=1
            this.addModel=true
            this.fields=data
            this.defaultAddress=[data.province,data.city,data.district,data.address]
            this.fields.addressValue=this.defaultAddress
            if(this.type==0){
                this.title="修改学校"
            }else{
                this.title="修改企业"
            }
        },
    }
}
</script>
<style lang="stylus">
.users
    .content
        margin-top:69px;
        position:relative;
        .tableWrapUl
            position:absolute;
            top:-61px;
            left:0;
.addUser
    #eform
        .ant-col-6
            width:25%
.addSchoolUser
    .has-feedback
        .ant-form-item-children-icon
            right:-30px;


</style>
